package lxf.qs.com;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.HeadlessException;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.HashMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class qs {
	
	public static void main(String[] args) {
		Domain damain = new Domain();
		damain.doThing();
	}
}

class Domain{
	 File anFile;
	 FileTool myFile;
	 JsonTool myJson;
	 GUITool myGUI;
	 String judgeTitle="";
	 String myfileFloder="D:\\QS2015\\remote\\";
	 String myfileAdr="D:\\QS2015\\remote\\QSData.txt";
	 String myfileFloderLocal="D:\\QS2015\\temp\\";
	 String myfileAdrLocal="D:\\QS2015\\temp\\QSData.txt";
	 FtpTool ftpTool;
	 int sendCon;
	 boolean isConnect;
	 InetAddress ad;
	public Domain() {
		super();
		ftpTool = new FtpTool("sk595.webcname.net","Web/QS2015/","ftp431442","LXFlxf158");
		ftpTool.connectFtp();
		sendCon=0;
		isConnect=true;
		myFile = new FileTool();
		myJson = new JsonTool();
		myGUI= new GUITool();
		myGUI.GUIInit();
		myFile.createFolder(myfileFloder);
		myFile.createFolder(myfileFloderLocal);
	}
	
	public void doThing(){
		judgeNet();
		myGUI.butAdd.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				myGUI.myFrame.remove(myGUI.panel21);
				myGUI.myFrame.add(myGUI.panel1,BorderLayout.NORTH);
				myGUI.myFrame.add(myGUI.panel11,BorderLayout.CENTER);
				myGUI.myFrame.setSize(800,601);//加上下面的设置大小代码，是为了解决窗体下面两个按钮显示问题。
				myGUI.myFrame.setVisible(true);
				myGUI.message.setText("");
			}
		});
		
		myGUI.butLook.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				myGUI.myFrame.remove(myGUI.panel11);
				myGUI.myFrame.add(myGUI.panel1,BorderLayout.NORTH);
				myGUI.myFrame.add(myGUI.panel21,BorderLayout.CENTER);
				myGUI.myFrame.setSize(800,600);
				myGUI.myFrame.setVisible(true);
				myGUI.message.setText("");
			}
		});
		
		myGUI.butClear.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				myGUI.message.setText("");
				myGUI.textTitle.append("");
				myGUI.textTitle.setText("");
				myGUI.textAnswer.append("");
				myGUI.textAnswer.setText("");
			}
		});
		
		myGUI.butChoose.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				JSONObject json = new JSONObject();
				String jsonContent="";
				String jsonContentNew="";
				JSONArray jsonArray = null;
				JSONArray jsonArrayNew = null;
				JFileChooser fc = new JFileChooser();
				fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
				fc.showDialog(new JLabel(), "选择");
				anFile = fc.getSelectedFile();
				try {
					jsonContent = myFile.readFile(myfileAdr);
					jsonContentNew = myFile.readFile(anFile.getPath().toString());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				HashMap<String,String> hashData = new HashMap<String,String>();
				jsonArray = JSONArray.fromObject(jsonContent);
				jsonArrayNew = JSONArray.fromObject(jsonContentNew);
				myJson.getJsonArray(hashData,jsonContent);
				int len = jsonArrayNew.size();
				for(int i=0;i<len;i++){
					json = (JSONObject) jsonArrayNew.get(i);
					json.get("question");
					if(!hashData.containsKey(json.get("question"))){
						jsonArray.add(json);
					} 
				}	
				try {
					myFile.writeFile(myfileAdr,jsonArray.toString());
				} catch (IOException e1) {
					myGUI.message.setText("写入文件错误");
				}
			}
		});
		
		myGUI.butSend.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				judgeNet();
				if(isConnect==false){
					JOptionPane.showMessageDialog(null,"网络连接失败");
					return;
				}
				if(sendCon==0){
					JOptionPane.showMessageDialog(null,"请在搜索框输入邮箱，不输入则上传默认邮箱");
					sendCon=1;
				}else{
					String email="1174254785@qq.com";
					String input = myGUI.textWord.getText();
					if(!input.equals("")){
						String matchEmail="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
						if(!input.matches(matchEmail)){
							JOptionPane.showMessageDialog(null,"邮箱格式错误");
							sendCon=0;
							return;
						}
						email=input;
					}
					Calendar calendar = Calendar.getInstance();
					int year = calendar.get(Calendar.YEAR);
					int month = calendar.get(calendar.MONTH)+1;
					int day = calendar.get(calendar.DATE);
					String title = "QS2015"+year+"-"+(month+1)+"-"+day;
					Email m = new Email();
					m.toAddressWithFile(email,title,"保存",myfileAdr);
					sendCon=0;
					JOptionPane.showMessageDialog(null,"上传成功，可能会延时");
				}
			}
		});
		
		myGUI.butConfirm.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				judgeNet();
				if(isConnect==false){
					String question = myGUI.textTitle.getText().toString();
					String jsonContent="";
					if(question.isEmpty()){
						JOptionPane.showMessageDialog(null,"请输入问题");
						return;
					}
					if(judgeTitle.equals(question)){
						JOptionPane.showMessageDialog(null,"已添加");
						return;
					}
					try {
						if(myFile.judgeFile(myfileAdr)){
							try {
								jsonContent = myFile.readFile(myfileAdr);
							} catch (IOException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							}
							myJson.readJosn(jsonContent);
							HashMap<String,String> hashData = new HashMap<String,String>();
							myJson.getJsonArray(hashData,jsonContent);	
							if(hashData.containsKey(question)){
								JOptionPane.showMessageDialog(null,"已存在该问题");
								return;
							} 
						}
					} catch (IOException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					Calendar calendar = Calendar.getInstance();
					String classify = myGUI.myChoice.getSelectedItem().toString();
					String answer = myGUI.textAnswer.getText().toString();
					int year = calendar.get(Calendar.YEAR);
					int month = calendar.get(calendar.MONTH)+1;
					int day = calendar.get(calendar.DATE);
					JSONArray jsonArray = new JSONArray();
					JSONObject json = new JSONObject();
					try {
						jsonContent = myFile.readFile(myfileAdr);
						if(jsonContent.length()==0){
							
						}else{
						//jsonContentPut = jsonContent.substring(1,jsonContent.length());
						jsonArray = JSONArray.fromObject(jsonContent);
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					json.put("classify",classify);
					json.put("year",year);
					json.put("month",month);
					json.put("day",day);
					json.put("question",question);
					json.put("answer",answer);
					jsonArray.add(json);
					try {
						myFile.writeFile(myfileAdr,jsonArray.toString());
						myFile.writeFile(myfileAdrLocal,jsonArray.toString());
						myGUI.message.setText("OK");
					} catch (IOException e1) {
						myGUI.message.setText("写入文件错误");
					}

				}else{
					String question = myGUI.textTitle.getText().toString();
					String jsonContent="";
					if(question.isEmpty()){
						JOptionPane.showMessageDialog(null,"请输入问题");
						return;
					}
					if(judgeTitle.equals(question)){
						JOptionPane.showMessageDialog(null,"已添加");
						return;
					}
					/*if(myFile.getFileLength(myfileFloder)<3){   //1.0版本，本地文件读取
						
					} else
						try {
							if(!myFile.judgeFile(myfileAdr)){
								
								}else{
									try {
									jsonContent = myFile.readFile(myfileAdr);
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								HashMap<String,String> hashData = new HashMap<String,String>();
								myJson.getJsonArray(hashData,jsonContent);
								if(hashData.containsKey(question)){
									JOptionPane.showMessageDialog(null,"已存在该问题");
									return;
								} 
							}
						} catch (HeadlessException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						} catch (IOException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}*/
					try {
						ftpTool.downFile(myfileFloder,"QSData.txt");
					} catch (Exception e2) {
						// TODO: handle exception
						myGUI.message.setText("下载文件异常");
						return;
					}
					try {
						jsonContent = myFile.readFile(myfileAdr);
					} catch (IOException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					myJson.readJosn(jsonContent);
					HashMap<String,String> hashData = new HashMap<String,String>();
					myJson.getJsonArray(hashData,jsonContent);	
					if(hashData.containsKey(question)){
						JOptionPane.showMessageDialog(null,"已存在该问题");
						return;
					} 
					Calendar calendar = Calendar.getInstance();
					String classify = myGUI.myChoice.getSelectedItem().toString();
					String answer = myGUI.textAnswer.getText().toString();
					int year = calendar.get(Calendar.YEAR);
					int month = calendar.get(calendar.MONTH)+1;
					int day = calendar.get(calendar.DATE);
					JSONArray jsonArray = new JSONArray();
					JSONArray jsonArrayNew = new JSONArray();
					JSONObject json = new JSONObject();
					try {
						jsonContent = myFile.readFile(myfileAdr);
						if(jsonContent.length()==0){
							
						}else{
							jsonArray = JSONArray.fromObject(jsonContent);
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					json.put("classify",classify);
					json.put("year",year);
					json.put("month",month);
					json.put("day",day);
					json.put("question",question);
					json.put("answer",answer);
					jsonArray.add(json);
					
					try {
						if(myFile.judgeFileNotCreate(myfileAdrLocal)){
							String jsonContentNew="";    
							 try {
								jsonContentNew = myFile.readFile(myfileAdrLocal);
							} catch (IOException e3) {
								// TODO Auto-generated catch block
								e3.printStackTrace();
							}
							jsonArrayNew = JSONArray.fromObject(jsonContentNew);  //将本地临时文件合并到主文件。
							myJson.getJsonArray(hashData,jsonContent);
							int len = jsonArrayNew.size();
							for(int i=0;i<len;i++){
								json = (JSONObject) jsonArrayNew.get(i);
								json.get("question");
								if(!hashData.containsKey(json.get("question"))){
									jsonArray.add(json);
								} 
							}
							myFile.delete(myfileAdrLocal);
						}
					} catch (IOException e4) {
						// TODO Auto-generated catch block
						e4.printStackTrace();
					}
					
					
					try {
						myFile.writeFile(myfileAdr,jsonArray.toString());
					} catch (IOException e1) {
						myGUI.message.setText("写入文件错误");
					}
					try {
						//ftpTool.connectFtp();
						ftpTool.uploadFile("QSData.txt", jsonArray.toString());
						myGUI.message.setText("OK");
					} catch (Exception e2) {
						e2.printStackTrace();
						myGUI.message.setText("上传文件错误");
					}
				}
			}
		});
		
		myGUI.butSearch.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String jsonContent="";
				String mes = "";
				mes = myGUI.textWord.getText();
				try {
					jsonContent = myFile.readFile(myfileAdr);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				HashMap<String,String> hashData = new HashMap<String,String>();
				myJson.getJsonArray(hashData,jsonContent);
				String data1[][] = new String[hashData.size()][2];
				Object data2[] = hashData.keySet().toArray();
				String temp = "";
				String[] columnName = {"问题","答案"};
				int len=0;
				for(int i=0;i<hashData.size();i++){
					temp = data2[i].toString();
					if(temp.contains(mes)){
						data1[len][0] = temp;
						data1[len][1] = hashData.get(temp);
						len++;
					}
				}
				String[][] data3 = new String[len][2];
				for(int i=0;i<len;i++){
					data3[i][0]=data1[i][0];
					data3[i][1]=data1[i][1];
				}
				System.out.println("hashData.size()"+hashData.size());
				JTable table = new JTable(data3,columnName);
				
				//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//关闭自动变宽度
				table.getColumnModel().getColumn(0).setPreferredWidth(150);
				table.getColumnModel().getColumn(1).setPreferredWidth(630);
				JScrollPane pane = new JScrollPane(table);
				
				myGUI.panel23.removeAll();
				myGUI.panel23.setLayout(new BorderLayout());
				myGUI.panel23.add(pane,BorderLayout.CENTER);
				myGUI.panel21.add(myGUI.panel22,BorderLayout.NORTH);
				myGUI.panel21.add(myGUI.panel23,BorderLayout.CENTER);

				myGUI.myFrame.remove(myGUI.panel21);
				myGUI.myFrame.add(myGUI.panel1,BorderLayout.NORTH);
				myGUI.myFrame.add(myGUI.panel21,BorderLayout.CENTER);
				myGUI.myFrame.setVisible(true);
			}
		});
		myGUI.butShowAll.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String jsonContent="";
				String mes = "";
				mes = myGUI.textWord.getText();
				try {
					jsonContent = myFile.readFile(myfileAdr);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				HashMap<String,String> hashData = new HashMap<String,String>();
				myJson.getJsonArray(hashData,jsonContent);
				String data1[][] = new String[hashData.size()][2];
				Object data2[] = hashData.keySet().toArray();
				String temp = "";
				String[] columnName = {"问题","答案"};
				int len=0;
				for(int i=0;i<hashData.size();i++){
					temp = data2[i].toString();
					if(temp.contains(mes)){
						data1[len][0] = temp;
						data1[len][1] = hashData.get(temp);
						len++;
					}
				}
				String[][] data3 = new String[len][2];
				for(int i=0;i<len;i++){
					data3[i][0]=data1[i][0];
					data3[i][1]=data1[i][1];
				}
				System.out.println("hashData.size()"+hashData.size());
				JTable table = new JTable(data3,columnName);
				table.setDefaultRenderer(Object.class, new TableCellTextAreaRenderer()); //自动换行。
				//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//关闭自动变宽度
				table.getColumnModel().getColumn(0).setPreferredWidth(150);
				table.getColumnModel().getColumn(1).setPreferredWidth(630);
				JScrollPane pane = new JScrollPane(table);
				
				myGUI.panel23.removeAll();
				myGUI.panel23.setLayout(new BorderLayout());
				myGUI.panel23.add(pane,BorderLayout.CENTER);
				myGUI.panel21.add(myGUI.panel22,BorderLayout.NORTH);
				myGUI.panel21.add(myGUI.panel23,BorderLayout.CENTER);

				myGUI.myFrame.remove(myGUI.panel21);
				myGUI.myFrame.add(myGUI.panel1,BorderLayout.NORTH);
				myGUI.myFrame.add(myGUI.panel21,BorderLayout.CENTER);
				myGUI.myFrame.setVisible(true);
			}
		});
		

		myGUI.myFrame.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				judgeNet();
				if(isConnect)
				ftpTool.close();
				
/*				while(true){
					try {
						Thread.sleep(50);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					if(!ftpTool.ftpClient.isConnected()){
						thread.interrupt();
						break;
					}
				}*/
				System.exit(0);
			}
		});	
	}
	public void judgeNet(){
		try {
			ad = InetAddress.getByName("www.baidu.com");
			isConnect=true;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			isConnect=false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			isConnect=false;
		}
		if(isConnect==false){
			myGUI.messageNet.setText("网络未连接");
		}else{
			myGUI.messageNet.setText("");
		}
	}
}